/*
 @Date: 2022/4/30
 @Desc: 首页视图控制器
 */

import UIKit

class IPHomeHeaderReusableView: UICollectionReusableView,TZImagePickerControllerDelegate {
    
    static let reuseId = "home_header_view"
    var selectChiCun = ""
    
    @IBOutlet weak var flowLayout: UICollectionViewFlowLayout!
    @IBOutlet weak var collectionView: UICollectionView!
    
    private lazy var mDatasource = [IPHomeItem(iconName: "icon_gm", title: "通用"),
                                    IPHomeItem(iconName: "icon_building", title: "建筑工程"),
                                    IPHomeItem(iconName: "icon_gov", title: "公务员"),
                                    IPHomeItem(iconName: "icon_oc", title: "职业资格"),
                                    IPHomeItem(iconName: "icon_pc", title: "IT认证"),
                                    IPHomeItem(iconName: "icon_travel", title: "旅游签证"),
                                    IPHomeItem(iconName: "icon_ed", title: "学历考试"),
                                    IPHomeItem(iconName: "icon_more", title: "自定义规格")]
    
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        setupUI()
    }
    
    private func setupUI(){
        
        collectionView.layer.cornerRadius = 5
        collectionView.clipsToBounds = true
        
        let nib = UINib.init(nibName: "IPHomeFuncCell", bundle: .main)
        collectionView.register(nib, forCellWithReuseIdentifier: IPHomeFuncCell.reuseId)
        
        flowLayout.minimumLineSpacing = 0
        flowLayout.minimumInteritemSpacing = 0
    }
    
}
//MARK: UICollectionViewDataSource UICollectionViewDelegate
extension IPHomeHeaderReusableView: UICollectionViewDataSource,UICollectionViewDelegate {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return mDatasource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: IPHomeFuncCell.reuseId, for: indexPath) as! IPHomeFuncCell
        let item = mDatasource[indexPath.row]
        cell.setupData(item)
        return cell
    }
    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [Any]!, isSelectOriginalPhoto: Bool) {
        let vc = IPEditPhotoViewController()
        vc.chiCunStr = selectChiCun
//        ["295x413","413x579","259x377","413x531","389x566","413x625"][0]
        vc.selectImg = photos.first!
        getCurrentVc().show(vc, sender: nil)
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.row == 7{
            let alterController = UIAlertController(title: "请输入自定义照片宽高", message: nil, preferredStyle: .alert)
            alterController.addTextField { (textField: UITextField) -> Void in
                textField.placeholder = "请输入自定义证件照的宽（px）"
                textField.keyboardType = .numberPad
            }
            alterController.addTextField { (textField: UITextField) -> Void in
                textField.placeholder = "请输入自定义证件照的高（px）"
                textField.keyboardType = .numberPad
            }
            let action = UIAlertAction(title: "取消", style: .cancel) { (UIAlertAction) -> Void in
                
            }
            let action1 = UIAlertAction(title: "确定", style: .default) { [self](UIAlertAction) -> Void in
                let textfield1:UITextField = (alterController.textFields?.first)!
                let textfield2:UITextField = (alterController.textFields?.last)!
                selectChiCun = textfield1.text! + "x" + textfield2.text!
                let vc = TZImagePickerController(maxImagesCount: 1, delegate: self)!
                vc.allowTakeVideo = false //是否允许拍视频
                vc.allowPickingVideo = false //是否允许选择视频
                vc.circleCropRadius = Int((UIScreen.main.bounds.size.width - 60)/2)
                vc.modalPresentationStyle = .fullScreen
                getCurrentVc().present(vc, animated: true, completion: nil)
                
            }
            
            alterController.addAction(action)
            alterController.addAction(action1)
            getCurrentVc().present(alterController, animated: true) { () -> Void in
                
            }
        } else {
            let vc = TZImagePickerController(maxImagesCount: 1, delegate: self)!
            self.selectChiCun = ["215x310","413x531","300x400","240x320","413x531","413x625","150x200"][indexPath.item]
            vc.allowTakeVideo = false //是否允许拍视频
            vc.allowPickingVideo = false //是否允许选择视频
            vc.circleCropRadius = Int((UIScreen.main.bounds.size.width - 60)/2)
            vc.modalPresentationStyle = .fullScreen
            getCurrentVc().present(vc, animated: true, completion: nil)
        }
        
    }
    public func getCurrentVc() -> UIViewController{
        let rootVc = UIApplication.shared.keyWindow?.rootViewController
        let currentVc = getCurrentVcFrom(rootVc!)
        return currentVc
    }
    func getCurrentVcFrom(_ rootVc:UIViewController) -> UIViewController{
        var currentVc:UIViewController
        var rootCtr = rootVc
        if(rootCtr.presentedViewController != nil) {
            rootCtr = rootVc.presentedViewController!
        }
        if rootVc.isKind(of:UITabBarController.classForCoder()) {
            currentVc = getCurrentVcFrom((rootVc as! UITabBarController).selectedViewController!)
        }else if rootVc.isKind(of:UINavigationController.classForCoder()){
            currentVc = getCurrentVcFrom((rootVc as! UINavigationController).visibleViewController!)
        }else{
            currentVc = rootCtr
        }
        return currentVc
    }
}

//MARK: UICollectionViewDelegateFlowLayout
extension IPHomeHeaderReusableView: UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let totalWidth = collectionView.bounds.width - 1
        let totalHeight = collectionView.bounds.height - 1
        let width = totalWidth / 4
        let height = totalHeight / 2
        return CGSize.init(width: width, height: height)
    }
}
